﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using MyServer.Common;
using System.IO;
using FrameWork.Setting;

namespace MyServer.Udp
{
    [SettingParentDefine]
    public class UdpDataReader : DataReaderBase
    {
        private static object LockObj = new object();

        protected override System.IO.Stream GetStream(object Tag)
        {
            return UdpDataHolder.GetStream(((UdpPkgInfo)Tag).BindPoint.ToString());
        }

        protected override int GetDataAvilable(object Tag)
        {
            UdpPkgInfo Info = (UdpPkgInfo)Tag;
            if(Info.Client.Available==0)
            {
                return 0;
            }
            IPEndPoint EndP = new IPEndPoint(IPAddress.Any, 0);
            byte[] Buffer = Info.Client.Receive(ref EndP); 
            bool isNew = UdpDataHolder.CheckIsNewConnection(EndP.ToString());
            UdpDataHolder.AddData(EndP.ToString(), Buffer);
            if (isNew)
            {
                DataCenter.Listener.AddConnect(Tag,false);
            }
            if(Info.BindPoint.ToString()==(new IPEndPoint(IPAddress.Any,0)).ToString())
            {
                Info.BindPoint = EndP;
                return Buffer.Length;
            }
            if(EndP.ToString()==Info.BindPoint.ToString())
            {
                return Buffer.Length;
            }
            else
            {
                return UdpDataHolder.CheckDataAvilable(Info.BindPoint.ToString());
            }
        }

        public UdpDataReader(UdpCenter Center) : base(Center) 
        {
            this.ReadTimeout += UdpDataReader_ReadTimeout;
        }

        void UdpDataReader_ReadTimeout(object sender, ReadTimeoutEventArgs e)
        {
            UdpPkgInfo Info = (UdpPkgInfo)e.TimeoutPkg.Tag;
            UdpDataHolder.ClearData(Info.BindPoint.ToString());
        }
    }
}
